#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/7/29 16:22
# @Author  : 唐松
# @File    : mock_util.py
# @Software: PyCharm


import json
from unittest import mock


class MockUtil:


    @classmethod
    def patch_if_needed(cls, caseinfo: dict, real_send_func):
        """
        增强版 Mock：
        1. 固定响应：mock: {...}
        2. 链式响应：mock.chain: [{...},{...}]
        3. 动态匹配：mock.rules: [{when:{...},then:{...}}]
        """
        mock_cfg = caseinfo.get("mock")
        if not mock_cfg:                       # 无 mock 字段 → 直接真实请求
            return real_send_func

        # 链式响应
        if "chain" in mock_cfg:
            chain = mock_cfg["chain"]
            idx   = caseinfo.get("_mock_idx", 0)
            resp  = chain[idx % len(chain)]
            caseinfo["_mock_idx"] = idx + 1     # 存回用例 dict，生命周期仅当前用例
            return cls._build_mock_response(resp)

        # 动态匹配
        if "rules" in mock_cfg:
            request_json = caseinfo.get("request", {}).get("json") or {}
            for rule in mock_cfg["rules"]:
                if rule.get("when") == request_json:
                    return cls._build_mock_response(rule["then"])
            # 未命中 → 真实请求
            return real_send_func

        # 固定响应（兼容旧用例）
        return cls._build_mock_response(mock_cfg)

    # 工具：构造假 Response
    @staticmethod
    def _build_mock_response(data):
        class FakeResp:
            def __init__(self, d):
                self.status_code = d.get("status_code", 200)
                body = d.get("json", d.get("text", ""))
                self._content = json.dumps(body, ensure_ascii=False).encode()
                self.text = self._content.decode()

            def json(self):
                return json.loads(self._content)

        return mock.Mock(return_value=FakeResp(data))